<template>
  <div class="app-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="card-panel">
      <el-col :span="8">
        <el-card shadow="hover" class="card total-income">
          <div class="card-content">
            <div class="card-title">总收入金额</div>
            <div class="card-amount">¥{{ statistics.totalAmount || 0 }}</div>
            <div class="card-compare">本月总收入</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="card pending-amount">
          <div class="card-content">
            <div class="card-title">待分发金额</div>
            <div class="card-amount">¥{{ statistics.pendingAmount || 0 }}</div>
            <div class="card-count">{{ statistics.pendingCount || 0 }} 笔待分发</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="card distributed-amount">
          <div class="card-content">
            <div class="card-title">已分发金额</div>
            <div class="card-amount">¥{{ statistics.distributedAmount || 0 }}</div>
            <div class="card-count">本月已分发 {{ statistics.monthDistributedCount || 0 }} 笔</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 咨询师月度收入统计 -->
    <el-card class="counselor-stats">
      <template #header>
        <div class="card-header">
          <span class="header-title">咨询师月度收入统计</span>
          <div class="header-actions">
            <el-button type="primary" @click="openPriceDialog">设置价格</el-button>
            <el-date-picker
              v-model="monthPicker"
              type="month"
              placeholder="选择月份"
              format="YYYY年MM月"
              value-format="YYYY-MM"
              @change="handleMonthChange"
            />
          </div>
        </div>
      </template>
      <el-table :data="counselorStats" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="counselorName" label="咨询师" min-width="120" />
        <el-table-column prop="orderCount" label="订单数" width="100" align="center" />
        <el-table-column prop="totalAmount" label="总收入" width="150" align="right">
          <template #default="{ row }">
            <span class="amount">¥{{ row.totalAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="platformFee" label="平台费用" width="150" align="right">
          <template #default="{ row }">
            <span class="amount">¥{{ row.platformFee.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="counselorAmount" label="实际收入" width="150" align="right">
          <template #default="{ row }">
            <span class="amount highlight">¥{{ row.counselorAmount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="distributionStatus" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.distributionStatus === 'DISTRIBUTED' ? 'success' : 'warning'">
              {{ row.distributionStatus === 'DISTRIBUTED' ? '已分发' : '待分发' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分发记录列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="header-title">分发记录</div>
          <div class="header-actions">
            <el-button type="primary" @click="handleBatchDistribute" :disabled="!hasSelectedRecords">
              批量分发
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索工具栏 -->
      <div class="table-toolbar">
        <div class="left-section">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
          <el-input
            v-model="queryParams.counselorName"
            placeholder="咨询师姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
          <el-select v-model="queryParams.status" placeholder="分发状态" clearable style="width: 200px">
            <el-option label="待分发" value="PENDING" />
            <el-option label="已分发" value="DISTRIBUTED" />
          </el-select>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </div>
      </div>

      <!-- 分发记录表格 -->
      <el-table
        v-loading="loading"
        :data="records"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="counselorName" label="咨询师" min-width="120" />
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="counselorAmount" label="应发金额" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.counselorAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="distributionStatus" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.distributionStatus === 'DISTRIBUTED' ? 'success' : 'warning'">
              {{ row.distributionStatus === 'DISTRIBUTED' ? '已分发' : '待分发' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="distributionTime" label="分发时间" width="180" />
        <el-table-column prop="distributorName" label="操作人" width="120" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.distributionStatus === 'PENDING'"
              type="primary"
              link
              @click="handleDistribute(row)"
            >
              分发
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 分发对话框 -->
    <el-dialog
      :title="form.records.length > 0 ? '批量分发' : '收入分发'"
      v-model="dialogVisible"
      width="500px"
    >
      <div v-if="form.records.length > 0" class="batch-info">
        <div class="info-item">
          <span class="label">选中记录</span>
          <span class="value">{{ form.records.length }} 条</span>
        </div>
        <div class="info-item">
          <span class="label">总金额</span>
          <span class="value highlight">¥{{ batchTotalAmount.toFixed(2) }}</span>
        </div>
      </div>
      <el-form :model="form" label-width="100px">
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitDistribute">
          确 定
        </el-button>
      </template>
    </el-dialog>

    <!-- 价格设置弹窗 -->
    <el-dialog
      title="设置咨询价格"
      v-model="priceDialogVisible"
      width="500px"
    >
      <el-form :model="priceForm" label-width="120px">
        <el-form-item label="平台费率" required>
          <div class="platform-fee-rate">
            <el-input-number
              v-model="platformFeeRate"
              :min="0"
              :max="100"
              :precision="2"
              :step="1"
              placeholder="请输入费率"
              style="width: calc(100% - 100px)"
              controls-position="right"
            />
            <span class="unit">%</span>
            <el-button type="primary" @click="handleUpdateFeeRate" :loading="feeRateSubmitting">
              更新费率
            </el-button>
          </div>
        </el-form-item>
        <el-divider content-position="center">咨询师价格设置</el-divider>
        <el-form-item label="咨询师" required>
          <el-select 
            v-model="priceForm.counselorId" 
            placeholder="请选择咨询师" 
            style="width: 100%"
            @change="handleCounselorChange"
          >
            <el-option
              v-for="item in counselorList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="每小时价格" required>
          <el-input-number
            v-model="priceForm.pricePerHour"
            :min="0"
            :precision="2"
            :step="10"
            placeholder="请输入价格"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="priceForm.status">
            <el-radio label="ENABLED">启用</el-radio>
            <el-radio label="DISABLED">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="priceDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="priceSubmitting" @click="submitPrice">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getIncomeList, getIncomeStatistics, distributeIncome, setCounselorPrice, getCounselorPrice, getCounselorList, updateCounselorPrice, getPlatformAccount, updatePlatformFeeRate } from '@/api/payment'
import type { PaymentQuery, PaymentRecord } from '@/types/payment'
import type { Counselor, CounselorPrice, CounselorPriceForm } from '@/types/counselor'
import type { ApiResponse } from '@/types/common'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Money, Timer, Check, Share, Search, User, Refresh } from '@element-plus/icons-vue'

interface CounselorStat {
  counselorId: number
  counselorName: string
  orderCount: number
  totalAmount: number
  platformFee: number
  counselorAmount: number
  distributionStatus: 'PENDING' | 'DISTRIBUTED'
}

// 状态数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const total = ref(0)
const statistics = ref<any>({})

// 月份选择
const monthPicker = ref<string>()
const counselorStats = ref<CounselorStat[]>([])

// 查询参数
const queryParams = ref<PaymentQuery>({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  counselorName: '',
  status: undefined
})

// 日期范围
const dateRange = ref<[string, string]>()

// 分发记录数据
const records = ref<PaymentRecord[]>([])

// 选中记录
const selectedRecords = ref<PaymentRecord[]>([])

// 分发表单
const form = ref({
  orderNo: '',
  counselorName: '',
  counselorAmount: 0,
  remark: '',
  records: [] as Array<{
    orderNo: string
    counselorName: string
    counselorAmount: number
  }>
})

// 计算属性
const hasSelectedRecords = computed(() => selectedRecords.value.length > 0)

const batchTotalAmount = computed(() => {
  return selectedRecords.value.reduce((sum, record) => sum + record.counselorAmount, 0)
})

// 计算咨询师列表
const counselorList = computed(() => {
  // 从 records 中提取不重复的咨询师信息
  const uniqueCounselors = new Map()
  records.value.forEach(record => {
    if (record.counselorId && record.counselorName && !uniqueCounselors.has(record.counselorId)) {
      uniqueCounselors.set(record.counselorId, {
        id: record.counselorId,
        realName: record.counselorName
      })
    }
  })
  return Array.from(uniqueCounselors.values())
})

// 价格设置相关
const priceDialogVisible = ref(false)
const priceSubmitting = ref(false)
const priceForm = ref<CounselorPriceForm>({
  counselorId: undefined as unknown as number,
  pricePerHour: undefined as unknown as number,
  status: 'ENABLED'
})

// 平台费率相关
const platformFeeRate = ref<number>(0)
const feeRateSubmitting = ref(false)

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const [listRes, statsRes] = await Promise.all([
      getIncomeList({
        ...queryParams.value,
        startDate: dateRange.value?.[0],
        endDate: dateRange.value?.[1]
      }),
      getIncomeStatistics()
    ])
    
    // 处理收入列表数据
    records.value = listRes.data.records
    total.value = listRes.data.total
    
    // 按咨询师分组统计
    const counselorMap = new Map<number, CounselorStat>()
    records.value.forEach(record => {
      if (!counselorMap.has(record.counselorId)) {
        counselorMap.set(record.counselorId, {
          counselorId: record.counselorId,
          counselorName: record.counselorName || '',
          orderCount: 0,
          totalAmount: 0,
          platformFee: 0,
          counselorAmount: 0,
          distributionStatus: 'PENDING'
        })
      }
      
      const stat = counselorMap.get(record.counselorId)!
      stat.orderCount++
      stat.totalAmount += record.totalAmount
      stat.platformFee += record.platformFee
      stat.counselorAmount += record.counselorAmount
      if (record.distributionStatus === 'DISTRIBUTED') {
        stat.distributionStatus = 'DISTRIBUTED'
      }
    })
    
    counselorStats.value = Array.from(counselorMap.values())
    statistics.value = statsRes.data
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 处理月份变更
const handleMonthChange = (val: string) => {
  if (val) {
    const [year, month] = val.split('-')
    const startDate = `${year}-${month}-01`
    const lastDay = new Date(parseInt(year), parseInt(month), 0).getDate()
    const endDate = `${year}-${month}-${lastDay}`
    dateRange.value = [startDate, endDate]
  } else {
    dateRange.value = undefined
  }
  handleQuery()
}

// 处理查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  loadData()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderNo: '',
    counselorName: '',
    status: undefined
  }
  dateRange.value = undefined
  monthPicker.value = undefined
  handleQuery()
}

// 处理选择变更
const handleSelectionChange = (selection: PaymentRecord[]) => {
  selectedRecords.value = selection
}

// 处理分页变更
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page
  loadData()
}

// 处理每页数量变更
const handleSizeChange = (size: number) => {
  queryParams.value.pageSize = size
  loadData()
}

// 处理单条分发
const handleDistribute = (row: PaymentRecord) => {
  form.value = {
    orderNo: row.orderNo,
    counselorName: row.counselorName || '',
    counselorAmount: row.counselorAmount,
    remark: '',
    records: []
  }
  dialogVisible.value = true
}

// 处理批量分发
const handleBatchDistribute = () => {
  if (!selectedRecords.value.length) {
    ElMessage.warning('请选择要分发的记录')
    return
  }
  
  form.value = {
    orderNo: '',
    counselorName: '',
    counselorAmount: 0,
    remark: '',
    records: selectedRecords.value.map(record => ({
      orderNo: record.orderNo,
      counselorName: record.counselorName || '',
      counselorAmount: record.counselorAmount
    }))
  }
  dialogVisible.value = true
}

// 提交分发
const submitDistribute = async () => {
  if (submitting.value) return
  submitting.value = true
  
  try {
    await distributeIncome(form.value)
    ElMessage.success('分发成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('分发失败:', error)
    ElMessage.error('分发失败')
  } finally {
    submitting.value = false
  }
}

// 打开价格设置弹窗
const openPriceDialog = () => {
  priceForm.value = {
    counselorId: undefined as unknown as number,
    pricePerHour: undefined as unknown as number,
    status: 'ENABLED'
  }
  priceDialogVisible.value = true
}

// 处理咨询师选择变更
const handleCounselorChange = async (counselorId: number) => {
  if (!counselorId) return
  
  try {
    const res = await getCounselorPrice(counselorId)
    
    if (res.data) {
      const priceData = res.data
      priceForm.value.pricePerHour = priceData.pricePerHour
      priceForm.value.status = priceData.status
    }
  } catch (error) {
    console.error('获取价格设置失败:', error)
    ElMessage.error('获取价格设置失败')
  }
}

// 提交价格设置
const submitPrice = async () => {
  if (!priceForm.value.counselorId) {
    ElMessage.warning('请选择咨询师')
    return
  }
  
  if (!priceForm.value.pricePerHour && priceForm.value.pricePerHour !== 0) {
    ElMessage.warning('请输入有效的价格')
    return
  }
  
  priceSubmitting.value = true
  const priceData = {
    counselorId: priceForm.value.counselorId,
    pricePerHour: priceForm.value.pricePerHour,
    status: priceForm.value.status
  }

  try {
    // 先获取现有价格设置
    const existingPrice = await getCounselorPrice(priceForm.value.counselorId)
    
    if (existingPrice.data) {
      // 如果存在，则更新
      await updateCounselorPrice({
        ...priceData,
        id: existingPrice.data.id
      })
      ElMessage.success('更新成功')
    } else {
      // 如果不存在，则新增
      await setCounselorPrice(priceData)
      ElMessage.success('设置成功')
    }
    
    priceDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    priceSubmitting.value = false
  }
}

const handleUpdateFeeRate = async () => {
  if (feeRateSubmitting.value) return
  
  if (platformFeeRate.value < 0 || platformFeeRate.value > 100) {
    ElMessage.warning('费率必须在0-100之间')
    return
  }
  
  feeRateSubmitting.value = true
  try {
    await updatePlatformFeeRate(platformFeeRate.value)
    ElMessage.success('平台费率更新成功')
  } catch (error) {
    console.error('更新平台费率失败:', error)
    ElMessage.error('更新平台费率失败')
  } finally {
    feeRateSubmitting.value = false
  }
}

const loadPlatformFeeRate = async () => {
  try {
    const res = await getPlatformAccount()
    if (res.data) {
      platformFeeRate.value = res.data.platformFeeRate
    }
  } catch (error) {
    console.error('获取平台费率失败:', error)
    ElMessage.error('获取平台费率失败')
  }
}

onMounted(() => {
  loadData()
  loadPlatformFeeRate()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .card-panel {
    margin-bottom: 24px;

    .card {
      height: 160px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 24px;
      background: #fff;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
      }

      .card-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 16px;
      }

      .card-amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 16px;
      }

      .card-count {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .counselor-stats {
    margin-bottom: 24px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-title {
        font-size: 16px;
        font-weight: bold;
      }

      .header-actions {
        display: flex;
        gap: 16px;
        align-items: center;
      }
    }

    .amount {
      font-family: Monaco, monospace;
      
      &.highlight {
        color: #409eff;
        font-weight: bold;
      }
    }
  }

  .list-card {
    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-title {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .table-toolbar {
      margin-bottom: 16px;
      
      .left-section {
        display: flex;
        gap: 16px;
        align-items: center;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .batch-info {
    background: #f5f7fa;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 20px;

    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #606266;
      }

      .value {
        font-weight: bold;
        
        &.highlight {
          color: #409eff;
        }
      }
    }
  }

  .platform-fee-rate {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .unit {
      margin: 0 8px;
      color: #606266;
    }
  }
}
</style> 